package com.mo.lib.ui.activity

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.databinding.ViewDataBinding
import com.mo.lib.ui.action.HandlerAction
import com.mo.lib.utils.KLog
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType

/**
 * @ author：mo
 * @ data：2022/3/21:15:40
 * @ 功能：ViewDataBinding基类
 * 注意：继承此类的子类里不能再有泛型了，否则反射会出错
 */

abstract class BaseVbActivity<VB : ViewDataBinding>() : BaseActivity(0),  HandlerAction {
    lateinit var viewBinding: VB
    override fun initView(savedInstanceState: Bundle?) {
        val view = initViewBinding()
        setContentView(view)
        getTitleView()?.let {
            ((viewBinding.root) as LinearLayout).addView(it,0)
        }
    }

    private fun initViewBinding(): View {
        val superclass = javaClass.genericSuperclass
        val aClass = (superclass as ParameterizedType).actualTypeArguments[0] as Class<*>
        try {
            val method: Method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
            viewBinding = method.invoke(null, layoutInflater) as VB
        } catch (e: NoSuchMethodException) {
            KLog.e(e.message!!)
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            KLog.e(e.message!!)
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            KLog.e(e.message!!)
            e.printStackTrace()
        }
        return viewBinding.root
    }

    open fun getTitleView() :View?=null
}